<template>
  <div class="portfolio-chart">
    <div class="chart-header">
      <h3 class="chart-title">{{ $t('portfolioChart.title') }}</h3>
      <div class="chart-total">
        <span class="total-label">{{ $t('portfolioChart.totalAssets') }}</span>
        <span class="total-value">{{ formatKRW(totalValue) }}</span>
      </div>
    </div>
    
    <div class="chart-container">
      <div ref="chartRef" class="chart-element"></div>
    </div>
    
    <div class="legend-container">
      <div class="legend-grid">
        <div 
          v-for="item in portfolioData" 
          :key="item.asset"
          class="legend-item"
        >
          <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
          <div class="legend-info">
            <span class="legend-label">{{ item.asset }}</span>
            <div class="legend-values">
              <span class="legend-value">{{ formatKRW(item.value) }}</span>
              <span class="legend-percentage">{{ item.percentage.toFixed(1) }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { walletApiService, type PortfolioDistribution } from '@/services/walletApi'
import { formatKRW } from '@/utils/currency'

const { t: $t } = useI18n()

const chartRef = ref<HTMLElement>()
let chartInstance: ECharts | null = null

const portfolioData = ref<PortfolioDistribution[]>([])

const totalValue = computed(() => {
  return portfolioData.value.reduce((sum, item) => sum + item.value, 0)
})

const loadPortfolioData = async () => {
  try {
    portfolioData.value = await walletApiService.getPortfolioDistribution()
    updateChart()
  } catch (error) {
    console.error('포트폴리오 데이터 로드 실패:', error)
  }
}

const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e2e8f0',
      textStyle: { color: '#374151' },
      formatter: (params: any) => {
        const { name, value, percent } = params
        return `
          <div style="padding: 8px;">
            <div style="font-weight: 600; margin-bottom: 4px;">${name}</div>
            <div style="color: #64748b;">${$t('portfolioChart.value')}: ${formatKRW(value)}</div>
            <div style="color: #64748b;">${$t('portfolioChart.ratio')}: ${percent}%</div>
          </div>
        `
      }
    },
    legend: {
      show: false
    },
    series: [
      {
        name: $t('portfolioChart.portfolioName'),
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 600,
            color: '#1a202c',
            formatter: (params: any) => {
              return `${params.percent}%`
            }
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.1)'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }

  chartInstance.setOption(option)
  updateChart()
  
  // 响应式调整
  const resizeObserver = new ResizeObserver(() => {
    chartInstance?.resize()
  })
  resizeObserver.observe(chartRef.value)
}

const updateChart = () => {
  if (!chartInstance || !portfolioData.value.length) return

  const chartData = portfolioData.value.map(item => ({
    name: item.asset,
    value: item.value,
    itemStyle: {
      color: item.color
    }
  }))

  chartInstance.setOption({
    series: [{ data: chartData }]
  })
}

onMounted(async () => {
  await loadPortfolioData()
  await initChart()
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped lang="scss">
.portfolio-chart {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
  height: 100%;
  display: flex;
  flex-direction: column;

  .chart-header {
    margin-bottom: 20px;

    .chart-title {
      font-size: 18px;
      font-weight: 600;
      color: #1a202c;
      margin: 0 0 8px 0;
    }

    .chart-total {
      display: flex;
      align-items: center;
      gap: 8px;

      .total-label {
        font-size: 12px;
        color: #64748b;
      }

      .total-value {
        font-size: 16px;
        font-weight: 600;
        color: #1a202c;
      }
    }
  }

  .chart-container {
    flex: 1;
    min-height: 250px;

    .chart-element {
      width: 100%;
      height: 100%;
    }
  }

  .legend-container {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #f1f5f9;

    .legend-grid {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 0;

        .legend-color {
          width: 12px;
          height: 12px;
          border-radius: 3px;
          flex-shrink: 0;
        }

        .legend-info {
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .legend-label {
            font-size: 13px;
            color: #374151;
            font-weight: 500;
          }

          .legend-values {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 2px;

            .legend-value {
              font-size: 12px;
              color: #1a202c;
              font-weight: 600;
            }

            .legend-percentage {
              font-size: 11px;
              color: #64748b;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .portfolio-chart {
    padding: 16px;

    .chart-container {
      min-height: 200px;
    }

    .legend-container {
      .legend-grid {
        .legend-item {
          .legend-info {
            .legend-values {
              flex-direction: row;
              gap: 8px;
              align-items: center;
            }
          }
        }
      }
    }
  }
}
</style>